package com.lihao.walkers.permissions_utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.Size;

import java.util.Arrays;
import java.util.List;

import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * 权限申请工具类。
 * @author lihao
 */
public class PermissionsUtils {

    /** 自身对象。 */
    private static PermissionsUtils mThis = null;

    /** 权限请求提示语。 */
    private static String mTip = null;

    /** 待请求的权限列表。 */
    private static String[] mPermissions = null;

    /** 待执行的任务。 */
    private static Runnable mTask = null;

    /** 权限申请专用Activity。 */
    public static class PermissionsActivity extends Activity implements EasyPermissions.PermissionCallbacks {

        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            Bundle bundle = getIntent().getExtras();
            // 获取参数。
            mTip = bundle.getString(Constants.PERMISSIONS_TIP);
            mPermissions = bundle.getStringArray(Constants.PERMISSIONS_CONTENT);
            // 开始申请权限。
            startRequest(mTip, mPermissions);
        }

        @Override
        public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
            if (mPermissions.length == perms.size()) { // 全部权限申请成功。
                if (mTask != null) {
                    mTask.run();
                }
                mTask = null;
                finish();
            }
        }

        @Override
        public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
            boolean deniedCheck = EasyPermissions.somePermissionDenied(this, mPermissions);
            boolean permanentlyDeniedCheck = EasyPermissions.somePermissionPermanentlyDenied(this, Arrays.asList(mPermissions));
            if (!deniedCheck && permanentlyDeniedCheck) {
                new AppSettingsDialog.Builder(this)
                        .setTitle(R.string.tip)
                        .setRationale(R.string.permissions_check_tip)
                        .setPositiveButton(R.string.confirm)
                        .setNegativeButton(R.string.cancel)
                        .build()
                        .show();
            }
            finish();
        }

        @Override
        public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
        }

        /**
         * 开始申请权限，并执行任务。
         * @param tip 提示语。
         * @param permissions 待申请的权限。
         */
        private void startRequest(@NonNull String tip, @Size(min = 1) String... permissions) {
            boolean hasPermissions = EasyPermissions.hasPermissions(this, permissions);
            if (hasPermissions) {
                if (mTask != null) {
                    mTask.run();
                }
                mTask = null;
                finish();
            } else {
                boolean deniedCheck = EasyPermissions.somePermissionDenied(this, mPermissions);
                if (!deniedCheck) {
                    new AlertDialog.Builder(this)
                            .setMessage(tip)
                            .setPositiveButton(R.string.confirm, (dialogInterface, i) -> {
                                EasyPermissions.requestPermissions(this, tip, Constants.REQUEST_CODE, permissions);
                                dialogInterface.dismiss();
                            })
                            .setNegativeButton(R.string.cancel, (dialogInterface, i) -> {
                                dialogInterface.dismiss();
                                finish();
                            })
                            .create()
                            .show();
                } else {
                    EasyPermissions.requestPermissions(this, tip, Constants.REQUEST_CODE, permissions);
                }
            }
        }
    }

    private PermissionsUtils(){

    }

    public static PermissionsUtils getInstance(){
        if (mThis == null) {
            mThis = new PermissionsUtils();
        }
        return mThis;
    }

    /**
     * 申请权限。
     * @param context 当前上下文。
     * @param tip 权限申请提示语，可解释权限用途。
     * @param permissions 待申请的权限列表。
     * @param work 权限申请成功后要执行的回调。
     */
    public void requestPermissions(Context context, @NonNull String tip, @Size(min = 1) String[] permissions, @NonNull Runnable work) {
        mTask = work;
        Intent intent = new Intent(context, PermissionsActivity.class);
        intent.putExtra(Constants.PERMISSIONS_TIP, tip);
        intent.putExtra(Constants.PERMISSIONS_CONTENT, permissions);
        context.startActivity(intent);
    }
}
